﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestorSQL.GUI.Security;
using GestorSQL.Utility;
using GestorSQL.GUI.Properties;
using GestorSQL.BLL.QueryExecutions;
using System.Threading;
using GestorSQL.BLL;
using GestorSQL.BusinessEntities;
using GestorSQL.Security.Interface;

namespace GestorSQL.GUI
{
    public partial class MainWindow : Form
    {
        private List<string> _casosAbiertos = new List<string>();
        private SolutionManager _solutionManager = new SolutionManager();
        private ConnectionManager _connectionManager = new ConnectionManager();
        private bool EsCasoParaAuthorizar = false;


        public MainWindow()
        {
            InitializeComponent();
        }

        #region File Menu Actions
        private void Login_Click(object sender, EventArgs e)
        {
            ShowLoginForm();
        }

        private void LogOut_Click(object sender, EventArgs e)
        {
            foreach (Form form in this.MdiChildren)
                form.Close();
            LogInWindow.Logout();
            EnableFormActions(false);
            ShowLoginAction(true);
            EnableLoginAction(true);
            EnableAccessResources(false);
        }

        private void ShowNewForm(object sender, EventArgs e)
        {
            NewCaseWindow newForm = new NewCaseWindow();
            DialogResult dr = newForm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                QueryWindow childForm = new QueryWindow(newForm.CaseNumber, newForm.OwnerUserName);
                childForm.MdiParent = this;
                childForm.Show();
                childForm.FormClosed += new FormClosedEventHandler(childForm_FormClosed);
                _casosAbiertos.Add(childForm.CaseNumber);
            }
        }

        private void OpenCase(object sender, EventArgs e)
        {
            OpenCaseWindow openForm = new OpenCaseWindow();
            DialogResult dr = openForm.ShowDialog();
            if (dr == DialogResult.OK)
            {

                CaseManager _caseManager = new CaseManager();

                if (_caseManager.CasoParaAutorizar(openForm.CaseNumber))
                {
                    AuthorizationWindow authorizationWindow = new AuthorizationWindow(openForm.CaseNumber);
                    if (authorizationWindow.ShowDialog().Equals(DialogResult.OK))
                    {
                        if (GetCurrentQueryWindow() != null)
                            GetCurrentQueryWindow().Close();


                    }
                }
                else
                {
                    EsCasoParaAuthorizar = false;
                    QueryWindow childForm = new QueryWindow(openForm.CaseNumber);
                    childForm.MdiParent = this;
                    childForm.Show();
                    childForm.FormClosed += new FormClosedEventHandler(childForm_FormClosed);
                    _casosAbiertos.Add(childForm.CaseNumber);

                    if (childForm.IsConnectionSetted)
                        connectionToolStripTextBox.Text = string.Format("{0} - {1}", childForm.Connection.Servidor, childForm.Connection.Nombre);
                  
                        
                    Caso currentCase = childForm.CaseManager.CurrentCase;

                    Resultado result = childForm.CaseManager.CasoParaEjecutarEnProduccion;

                    if (result.Equals(Resultado.Exitoso))
                    {
                        EsCasoParaAuthorizar = true;
                        childForm.SetProductionConnection(currentCase.Conexion1);

                        rechazarToolStripButton.Visible = true;
                        connectionToolStripButton.Visible = false;
                        connectionToolStripTextBox.Enabled = false;
                    }
                    else if (result.Equals(Resultado.FechaInvalida))
                    {
                        connectionToolStripTextBox.Text = string.Empty;
                        this.GetCurrentQueryWindow().Close();
                        MessageBox.Show(string.Format(Properties.Resources.Solution_InvalidRangeDate, currentCase.Solucion.FechaInicio, currentCase.Solucion.FechaFin));
                    }

                }
            }
        }

        private void childForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _casosAbiertos.Remove(((QueryWindow)sender).CaseNumber);

            rechazarToolStripButton.Visible = false;
            connectionToolStripButton.Visible = true;
            connectionToolStripTextBox.Enabled = true;

        }

        private void viewCaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewCase viewCaseWindow = new ViewCase();
            viewCaseWindow.MdiParent = this;
            viewCaseWindow.Show();

        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region Edit Menu Actions
        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!IsQueryWindow())
                return;
            QueryWindow qwindow = GetCurrentQueryWindow();
            qwindow.ProcessKbdCtrlShortcuts(new KeyEventArgs(((ToolStripMenuItem)sender).ShortcutKeys));
            redoToolStripMenuItem.Enabled = qwindow.CanRedo;
            undoToolStripMenuItem.Enabled = qwindow.CanUndo;
        }
        #endregion

        #region View Menu Actions
        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }
        #endregion

        #region Tools Menu Actions

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {

            ManagementTools mgmTools = new ManagementTools();
            DialogResult dr = mgmTools.ShowDialog();
        }

        #endregion

        #region Buil Menu Actions
        private void executeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Execute(false);
        }

        private void executeSelectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Execute(true);
        }

        private void _Execute(bool selected)
        {
            if (!_ValidateExecution(selected))
                return;
            QueryWindow qwindow = GetCurrentQueryWindow();
            ResultTarget target = resultadoEnGrillaToolStripMenuItem.Checked ? ResultTarget.Grid :
                                  resultadoEnPlanoToolStripMenuItem.Checked ? ResultTarget.Text :
                                  ResultTarget.None;


            qwindow.Execute(selected, target);
        }

        private bool _ValidateExecution(bool selected)
        {
            if (!IsQueryWindow())
                return false;
            QueryWindow qwindow = GetCurrentQueryWindow();
            if (!qwindow.IsConnectionSetted)
            {
                MessageBox.Show(Resources.MainWindow_NonConnectionSetted, Resources.MainWindow_WindowText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (selected && !qwindow.IsTextSelected)
            {
                MessageBox.Show(Resources.MainWindow_NonSelectedText, Resources.MainWindow_WindowText, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void connectionToolStripButton_Click(object sender, EventArgs e)
        {
            ConnectionWindow connForm = new ConnectionWindow(false);
            DialogResult dr = connForm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (!IsQueryWindow())
                    return;
                QueryWindow qwindow = GetCurrentQueryWindow();
                qwindow.SetConnection(connForm.Connection);
                connectionToolStripTextBox.Text = string.Format("{0} - {1}", connForm.Connection.Servidor, connForm.Connection.Nombre);
            }
        }

        private void solutionToolStripButton_Click(object sender, EventArgs e)
        {
            if (!IsQueryWindow())
                return;

            QueryWindow qwindow = GetCurrentQueryWindow();


            if (qwindow.CaseManager.CasoParaEjecutarEnProduccion.Equals(Resultado.Exitoso))
            {


                if (_solutionManager.GetLogsByBySolution(qwindow.CaseManager.GetCase(qwindow.CaseNumber).SolucionActual.Value).Count > 0)
                {
                    EnableFormActions(false);
                   

                    _solutionManager.CerrarSolucion(qwindow.CaseNumber,"Caso Ejecutado Correctamente y Solucionado.");

                    if (GetCurrentQueryWindow() != null)
                        GetCurrentQueryWindow().Close();
                }
                else
                    MessageBox.Show(Properties.Resources.Solution_CloseCaseNoneExecution);

            }

            else
            {
                SolutionWindow solForm = new SolutionWindow(qwindow.CaseManager);
                DialogResult dr = solForm.ShowDialog();
                if (dr == DialogResult.OK)
                {

                    if (GetCurrentQueryWindow() != null)
                        GetCurrentQueryWindow().Close();

                }
            }
        }

        private void rechazarToolStripButton_Click(object sender, EventArgs e)
        {
            QueryWindow qwindow = GetCurrentQueryWindow();
            TextWindow textWindow = new TextWindow(Properties.Resources.MainWindow_ReturnSolution, "",Properties.Resources.Description, false, false, true);
            if (textWindow.ShowDialog().Equals(DialogResult.OK) && !string.IsNullOrEmpty(textWindow.Texto))
            {
                _solutionManager.DevolverSolucion(qwindow.CaseManager.CurrentCase, textWindow.Texto);

                if (qwindow != null)
                    qwindow.Close();

            }

        }

        private void resultadoEnGrillaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            resultadoEnGrillaToolStripMenuItem.Checked = true;
            resultadoEnPlanoToolStripMenuItem.Checked = false;
        }

        private void resultadoEnPlanoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            resultadoEnGrillaToolStripMenuItem.Checked = false;
            resultadoEnPlanoToolStripMenuItem.Checked = true;
        }

        #endregion

        #region Window Menu Actions
        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }
        #endregion

        #region Help Menu Actions
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.MdiParent = this;
            about.Show();
        }
        #endregion

        #region Event Handlers
        private void MainWindow_Load(object sender, EventArgs e)
        {
            EnableFormActions(false);
            ShowLoginAction(true);
            ShowLoginForm();
        }

        private void loginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (((LogInWindow)sender).IsAuthenticated)
            {

                CustomPrincipal pr = (CustomPrincipal)Thread.CurrentPrincipal;

                EnableFormActions(true);
                //EnableSaveButtons(false);
                EnableAccessResources(false);

                ShowLoginAction(false);

                AssignAccessToResurces(pr.Roles);


            }
            else
            {
                EnableLoginAction(true);
            }
        }

        private void MainWindow_MdiChildActivate(object sender, EventArgs e)
        {
            bool isQueryWindow = IsQueryWindow();
            EnableSaveButtons(isQueryWindow);
            editMenu.Visible = isQueryWindow;
            buildToolStripMenuItem.Visible = isQueryWindow;
            connectionToolStripButton.Visible = isQueryWindow;
            connectionToolStripSeparator.Visible = isQueryWindow;
            connectionToolStripLabel.Visible = isQueryWindow;
            connectionToolStripTextBox.Visible = isQueryWindow;
            solutionToolStripButton.Visible = isQueryWindow;
            solutionToolStripSeparator.Visible = isQueryWindow;

            if (EsCasoParaAuthorizar)
            {
                rechazarToolStripButton.Visible = isQueryWindow;
                connectionToolStripButton.Visible = false;
            }

        }

        #endregion

        #region Private Methods
        private bool IsQueryWindow()
        {
            return (this.ActiveMdiChild != null && this.ActiveMdiChild.GetType().Equals(typeof(QueryWindow)));
        }

        private QueryWindow GetCurrentQueryWindow()
        {
            return (QueryWindow)(ActiveMdiChild);
        }

        private void ShowLoginForm()
        {
            EnableLoginAction(false);
            LogInWindow loginForm = new LogInWindow();
            loginForm.MdiParent = this;
            loginForm.FormClosed += new FormClosedEventHandler(loginForm_FormClosed);
            loginForm.Show();
        }

        private void EnableFormActions(bool enabled)
        {
            editMenu.Enabled = enabled;
            viewMenu.Enabled = enabled;
            toolsMenu.Enabled = enabled;
            windowsMenu.Enabled = enabled;

            newToolStripButton.Enabled = enabled;
            newToolStripMenuItem.Enabled = enabled;

            openToolStripButton.Enabled = enabled;
            openToolStripMenuItem.Enabled = enabled;

            saveToolStripButton.Enabled = enabled;
            saveToolStripMenuItem.Enabled = enabled;

            buildToolStripMenuItem.Enabled = enabled;
            connectionToolStripButton.Enabled = enabled;
            connectionToolStripLabel.Enabled = enabled;
            connectionToolStripTextBox.Enabled = enabled;

            solutionToolStripButton.Enabled = enabled;


        }

        private void ShowLoginAction(bool visible)
        {
            logInToolStripMenuItem.Visible = visible;
            logOutToolStripMenuItem.Visible = !visible;
            toolStripSeparator0.Visible = !visible;
        }

        private void EnableLoginAction(bool enabled)
        {
            logInToolStripMenuItem.Enabled = enabled;
        }

        private void EnableSaveButtons(bool enabled)
        {
            saveToolStripButton.Enabled = enabled;
            saveToolStripMenuItem.Enabled = enabled;
        }

        private void SaveCase(object sender, EventArgs e)
        {
            try
            {
                QueryWindow qwindow = GetCurrentQueryWindow();
                qwindow.SaveCase();
            }
            catch (Exception ex)
            {
                ex.Logg(LoggType.Error);
                MessageBox.Show(Resources.Error_Unexpected);
            }
        }

        #region Access Resources

        public void AssignAccessToResurces(string[] roles)
        {
            foreach (var role in roles)
                PermitAccessToResources(role, true);
        }

        public void EnableAccessResources(bool enable)
        {

            toolsMenu.Visible = enable;
            toolsMenu.Enabled = enable;

            newToolStripButton.Visible = enable;
            newToolStripButton.Enabled = enable;
          
            newToolStripMenuItem.Visible = enable;
            newToolStripMenuItem.Enabled = enable;

            openToolStripButton.Visible = enable;
            openToolStripButton.Enabled = enable;
            openToolStripMenuItem.Visible = enable;
            openToolStripMenuItem.Enabled = enable;

            viewCaseToolStripMenuItem.Visible = enable;
            viewCaseToolStripMenuItem.Enabled = enable;

            saveToolStripButton.Visible = enable;
            saveToolStripButton.Enabled = enable;
            saveToolStripMenuItem.Visible = enable;
            saveToolStripMenuItem.Enabled = enable;

            resultadoEnGrillaToolStripMenuItem.Visible = enable;
            resultadoEnGrillaToolStripMenuItem.Enabled = enable;

            toolStripSeparatorGuardar.Visible = enable;

        }

        public void PermitAccessToResources(string role, bool enable)
        {

            if (role.Equals(Role.ADMIN))
            {
                newToolStripButton.Visible = enable;
                newToolStripButton.Enabled = enable;

                newToolStripMenuItem.Visible = enable;
                newToolStripMenuItem.Enabled = enable;

                openToolStripButton.Visible = enable;
                openToolStripButton.Enabled = enable;
                openToolStripMenuItem.Visible = enable;
                openToolStripMenuItem.Enabled = enable;

                saveToolStripButton.Visible = enable;
                saveToolStripButton.Enabled = enable;

                saveToolStripMenuItem.Visible = enable;
                saveToolStripMenuItem.Enabled = enable;

                toolStripSeparatorGuardar.Visible = enable;
                
                resultadoEnGrillaToolStripMenuItem.Visible = enable;
                resultadoEnGrillaToolStripMenuItem.Enabled = enable;
                
                toolsMenu.Visible = enable;
                toolsMenu.Enabled = enable;
            }
            if (role.Equals(Role.ANALISTA))
            {
                newToolStripButton.Visible = enable;
                newToolStripButton.Enabled = enable;

                newToolStripMenuItem.Visible = enable;
                newToolStripMenuItem.Enabled = enable;

                openToolStripButton.Visible = enable;
                openToolStripButton.Enabled = enable;
                
                openToolStripMenuItem.Visible = enable;
                openToolStripMenuItem.Enabled = enable;

                openToolStripButton.Visible = enable;
                openToolStripButton.Enabled = enable;

                openToolStripMenuItem.Visible = enable;
                openToolStripMenuItem.Enabled = enable;

                saveToolStripButton.Visible = enable;
                saveToolStripButton.Enabled = enable;

                saveToolStripMenuItem.Visible = enable;
                saveToolStripMenuItem.Enabled = enable;

                toolStripSeparatorGuardar.Visible = enable;

                resultadoEnGrillaToolStripMenuItem.Visible = enable;
                resultadoEnGrillaToolStripMenuItem.Enabled = enable;
            }
            if (role.Equals(Role.AUTORIZADOR))
            {
                openToolStripButton.Visible = enable;
                openToolStripButton.Enabled = enable;

                openToolStripMenuItem.Visible = enable;
                openToolStripMenuItem.Enabled = enable;

            }
            if (role.Equals(Role.CONSULTAS))
            {
                viewCaseToolStripMenuItem.Visible = enable;
                viewCaseToolStripMenuItem.Enabled = enable;
            }

        }

        #endregion

        #endregion

    }
}
